/**
 * @date 2006-5-9 17:17:40
 *
 */
package org.nanhill.moo.dao.hibernate;

import java.util.Iterator;
import java.util.List;

import org.nanhill.moo.dao.CostDao;
import org.nanhill.moo.domain.Cost;
import org.nanhill.moo.domain.CostFactory;
import org.nanhill.support.hibernate.HibernateEntityManager;

/**
 * @author alin [xalinx at gmail dot com]
 * 
 */
public class CostDaoImpl extends HibernateEntityManager<Cost, Integer>
		implements CostDao {

	private boolean inited = false;

	/**
	 * Init Cost Factory.
	 */
	private void init() {
		// if inited , just return
		if (inited)
			return;
		// load costs from db
		List<Cost> costList = super.findAll();
		Cost[] costs = new Cost[costList.size()];
		for (Iterator<Cost> itt = costList.iterator(); itt.hasNext();) {
			Cost item = itt.next();
			int id = (int) item.getId();
			costs[id - 1] = item;
		}
		CostFactory.instance().reset(costs);
		// set inited tag
		inited = true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nanhill.moo.dao.CostDao#read(java.lang.String)
	 */
	public Cost findByName(String name) {
		init();
		return CostFactory.instance().getByName(name);
	}

	public Cost findById(Integer id) {
		init();
		return CostFactory.instance().get(id);
	}

	public Cost[] findAllToArray() {
		init();
		return CostFactory.instance().getAll();
	}

	public Cost[] findAllWithFavorCount() {
		init();
		Cost[] costs = CostFactory.instance().getAll();
		List list = getSession()
				.createQuery(
						"select f.cost.id, count(f.id) from Favor f group by f.cost.id")
				.list();
		for (Object item : list) {
			Object[] costCount = (Object[]) item;
			int costId = ((Long) costCount[0]).intValue();
			int favorCount = ((Long) costCount[1]).intValue();
			costs[costId - 1].setCount(favorCount);
		}
		return costs;
	}

	public Cost findByEnName(String enName) {
		init();
		return CostFactory.instance().getByEnName(enName);
	}

	@Override
	public int findCount() {
		init();
		return CostFactory.instance().getCount();
	}

}
